package com.muyu.cart.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.cart.constant.ProductStatusEnum;
import com.muyu.cart.domain.CartManager;
import com.muyu.cart.domain.req.*;
import com.muyu.cart.domain.resp.CartListResp;
import com.muyu.cart.domain.resp.CartStatusCheckResp;
import com.muyu.cart.mapper.CartManagerMapper;
import com.muyu.common.product.remote.ProductRemoteService;
import com.muyu.common.product.domain.*;
import com.muyu.cart.service.CartService;
import com.muyu.common.core.exception.ServiceException;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.core.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 购物车服务实现类
 *
 * @author JiaCheng
 * @version 1.0
 * @since 2025-09-21
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartManagerMapper, CartManager> implements CartService {

    @Autowired
    private CartManagerMapper cartManagerMapper;

    @Autowired
    private ProductRemoteService productRemoteService;

    @Override
    public List<CartListResp> selectCartListPage(CartListReq req) {
        return cartManagerMapper.selectCartListPage(req);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addToCart(CartAddReq req) {

        // 验证商品和SKU信息
        ProductInfo productInfo = getProductInfoSafely(req.getProductId());
        ProductSkuInfo skuInfo = getSkuInfoSafely(req.getSkuId());

        if(productInfo==null){
            throw new ServiceException("商品sku为空");
        }
        if(skuInfo==null){
            throw new ServiceException("sku信息为空");
        }

        // 检查库存
        if (!checkStockSafely(req.getSkuId(), req.getQuantity())) {
            throw new ServiceException("库存不足");
        }

        Long userId = SecurityUtils.getUserId();
        // 查询是否已存在该商品
        LambdaQueryWrapper<CartManager> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartManager::getUserId, userId)
                .eq(CartManager::getSkuId, req.getSkuId());
        
        CartManager existingCart = cartManagerMapper.selectOne(queryWrapper);
        
        if (existingCart != null) {
            // 商品已存在，更新数量
            LambdaUpdateWrapper<CartManager> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CartManager::getId, existingCart.getId())
                    .setSql("quantity = quantity + " + req.getQuantity())
                    .set(CartManager::getSkuPrice, skuInfo.getPrice())
                    .set(CartManager::getOriginPrice, skuInfo.getOriginalPrice())
                    .set(CartManager::getProductName, productInfo.getProductName())
                    .set(CartManager::getProductThumbnail, productInfo.getThumbnail())
                    .set(CartManager::getRemark, skuInfo.getSpecs())
                    .set(CartManager::getUpdateTime, LocalDateTime.now());
            
            int updateCount = cartManagerMapper.update(null, updateWrapper);
            if (updateCount == 0) {
                throw new ServiceException("更新购物车失败，请重试");
            }
        } else {
            // 商品不存在，新增记录
            CartManager cartManager = CartManager.builder()
                    .userId(userId)
                    .productId(req.getProductId())
                    .skuId(req.getSkuId())
                    .quantity(req.getQuantity())
                    .isSelected(true)
                    .isDeleted(false)
                    .skuPrice(skuInfo.getPrice())
                    .originPrice(skuInfo.getOriginalPrice())
                    .productName(productInfo.getProductName())
                    .productThumbnail(productInfo.getThumbnail())
                    .remark(skuInfo.getSpecs())
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();

            int insertCount = cartManagerMapper.insert(cartManager);
            if (insertCount == 0) {
                throw new ServiceException("添加购物车失败，请重试");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQuantity(CartUpdateQuantityReq req) {
        // 将字符串ID转换为Long
        Long cartIdLong = Convert.toLong(req.getCartId());
        CartManager cartManager = cartManagerMapper.selectById(cartIdLong);
        if (cartManager == null) {
            throw new ServiceException("购物车商品不存在");
        }
        Long userId = SecurityUtils.getUserId();
        if (!cartManager.getUserId().equals(userId)) {
            throw new ServiceException("购物车商品不存在");
        }

        if (req.getQuantity() <= 0) {
            throw new ServiceException("商品数量必须大于0");
        }

        // 检查库存
        if (!checkStockSafely(cartManager.getSkuId(), req.getQuantity())) {
            throw new ServiceException("库存不足");
        }

        // 更新数量
        cartManager.setQuantity(req.getQuantity());
        cartManager.setUpdateTime(LocalDateTime.now());
        cartManagerMapper.updateById(cartManager);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void toggleSelect(CartToggleSelectReq req) {
        Long userId = SecurityUtils.getUserId();
        LambdaUpdateWrapper<CartManager> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CartManager::getUserId, userId)
                .in(CartManager::getId, req.getCartIds())
                .set(CartManager::getIsSelected, req.getIsSelected())
                .set(CartManager::getUpdateTime, LocalDateTime.now());

        cartManagerMapper.update(null, updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void selectAll(CartSelectAllReq req) {
        Long userId = SecurityUtils.getUserId();

        LambdaUpdateWrapper<CartManager> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CartManager::getUserId, userId)
                .set(CartManager::getIsSelected, req.getIsSelected())
                .set(CartManager::getUpdateTime, LocalDateTime.now());

        cartManagerMapper.update(null, updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCartItems(List<Long> cartIds) {
        Long userId = SecurityUtils.getUserId();
        // 验证购物车商品是否属于当前用户
        LambdaQueryWrapper<CartManager> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartManager::getUserId, userId)
                .in(CartManager::getId, cartIds);
        
        List<CartManager> cartItems = cartManagerMapper.selectList(queryWrapper);
        if (cartItems.size() != cartIds.size()) {
            throw new ServiceException("部分购物车商品不存在或不属于当前用户");
        }

        // 真删除：直接从数据库中删除记录
        LambdaQueryWrapper<CartManager> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(CartManager::getUserId, userId)
                .in(CartManager::getId, cartIds);

        cartManagerMapper.delete(deleteWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearCart() {
        Long userId = SecurityUtils.getUserId();

        // 真删除：清空当前用户的所有购物车商品
        LambdaQueryWrapper<CartManager> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(CartManager::getUserId, userId);

        cartManagerMapper.delete(deleteWrapper);
        
    }

    @Override
    public int getTotalCount() {
        Long userId = SecurityUtils.getUserId();
        return cartManagerMapper.countCartItems(userId);
    }

    @Override
    public int getSelectedCount() {
        Long userId = SecurityUtils.getUserId();
        return cartManagerMapper.countSelectedItems(userId);
    }

    @Override
    public BigDecimal getSelectedAmount() {
        Long userId = SecurityUtils.getUserId();

        CartListReq req = new CartListReq();
        req.setUserId(userId);
        req.setOnlySelected(1);

        List<CartListResp> selectedItems = cartManagerMapper.selectCartListPage(req);
        if (selectedItems.isEmpty()) {
            return BigDecimal.ZERO;
        }

        // 获取SKU信息
        List<Long> skuIds = selectedItems.stream()
                .map(item -> Long.parseLong(item.getSkuId()))
                .distinct()
                .collect(Collectors.toList());

        Map<Long, ProductSkuInfo> skuInfoMap = getBatchSkuInfoSafely(skuIds);

        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CartListResp item : selectedItems) {
            ProductSkuInfo skuInfo = skuInfoMap.get(Long.parseLong(item.getSkuId()));
            BigDecimal price = skuInfo != null ? skuInfo.getPrice() : item.getSkuPrice();
            totalAmount = totalAmount.add(calculateSubtotal(price, item.getQuantity()));
        }

        return totalAmount;
    }

    @Override
    public List<CartListResp> getSelectedItems() {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return new ArrayList<>();
        }

        CartListReq req = new CartListReq();
        req.setUserId(userId);
        req.setOnlySelected(1);

        return cartManagerMapper.selectCartListPage(req);
    }

    @Override
    public List<CartStatusCheckResp> checkCartStatus() {
        Long userId = SecurityUtils.getUserId();


        CartListReq req = new CartListReq();
        req.setUserId(userId);
        List<CartListResp> cartItems = cartManagerMapper.selectCartListPage(req);
        List<CartStatusCheckResp> statusList = new ArrayList<>();
        for (CartListResp item : cartItems) {
            CartStatusCheckResp status = new CartStatusCheckResp();
            status.setCartId(Long.parseLong(item.getId()));
            status.setSkuId(Long.parseLong(item.getSkuId()));
            status.setProductId(Long.parseLong(item.getProductId()));

            // 检查商品状态
            ProductInfo productInfo = getProductInfoSafely(Long.parseLong(item.getProductId()));
            if (productInfo == null) {
                status.setStatus(0);
                status.setStatusText("商品不存在");
                status.setCanPurchase(false);
            } else if (!ProductStatusEnum.ONLINE.getCode().equals(productInfo.getStatus())) {
                status.setStatus(1);
                status.setStatusText("商品已下架");
                status.setCanPurchase(false);
            } else {
                // 检查库存
                if (checkStockSafely(Long.parseLong(item.getSkuId()), item.getQuantity())) {
                    status.setStatus(2);
                    status.setStatusText("正常");
                    status.setCanPurchase(true);
                } else {
                    status.setStatus(3);
                    status.setStatusText("库存不足");
                    status.setCanPurchase(false);
                }
            }

            statusList.add(status);
        }

        return statusList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mergeCart(List<CartManager> cartItems) {
        Long userId = SecurityUtils.getUserId();

        for (CartManager localItem : cartItems) {
            // 检查商品状态
            ProductInfo productInfo = getProductInfoSafely(localItem.getProductId());
            if (productInfo == null || !ProductStatusEnum.ONLINE.getCode().equals(productInfo.getStatus())) {
                continue;
            }

            // 检查SKU信息
            ProductSkuInfo skuInfo = getSkuInfoSafely(localItem.getSkuId());
            if (skuInfo == null) {
                continue;
            }

            // 检查库存
            if (!checkStockSafely(localItem.getSkuId(), localItem.getQuantity())) {
                continue;
            }

            // 查找是否已存在相同的SKU
            LambdaQueryWrapper<CartManager> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CartManager::getUserId, userId)
                    .eq(CartManager::getSkuId, localItem.getSkuId());
            CartManager existingCart = cartManagerMapper.selectOne(queryWrapper);

            if (existingCart != null) {
                // 更新现有商品
                existingCart.setQuantity(existingCart.getQuantity() + localItem.getQuantity());
                existingCart.setSkuPrice(skuInfo.getPrice());
                existingCart.setRemark(skuInfo.getSpecs());
                existingCart.setUpdateTime(LocalDateTime.now());
                cartManagerMapper.updateById(existingCart);
            } else {
                // 新增商品
                localItem.setUserId(userId);
                localItem.setSkuPrice(skuInfo.getPrice());
                localItem.setRemark(skuInfo.getSpecs());
                localItem.setCreateTime(LocalDateTime.now());
                localItem.setUpdateTime(LocalDateTime.now());
                cartManagerMapper.insert(localItem);
            }
        }
    }





    /**
     * 安全获取商品信息
     */
    private ProductInfo getProductInfoSafely(Long productId) {
        try {
            Result<ProductInfo> result = productRemoteService.getProductInfo(productId);
            if (result != null && Result.isSuccess(result) && result.getData() != null) {
                return result.getData();
            }
        } catch (Exception e) {
            throw new ServiceException("");
        }
        return null;
    }



    /**
     * 安全获取SKU信息
     */
    private ProductSkuInfo getSkuInfoSafely(Long skuId) {
        try {
            Result<ProductSkuInfo> result = productRemoteService.getSkuInfo(skuId);
            if (result != null && Result.isSuccess(result) && result.getData() != null) {
                return result.getData();
            }
        } catch (Exception e) {
            throw new ServiceException("");
        }
        return null;
    }

    /**
     * 批量安全获取SKU信息
     */
    private Map<Long, ProductSkuInfo> getBatchSkuInfoSafely(List<Long> skuIds) {
        try {
            Result<List<ProductSkuInfo>> result = productRemoteService.getBatchSkuInfo(skuIds);
            if (result != null && Result.isSuccess(result) && result.getData() != null) {
                return result.getData().stream()
                        .collect(Collectors.toMap(ProductSkuInfo::getSkuId, sku -> sku));
            }
        } catch (Exception e) {
            throw new ServiceException("");
        }
        return new HashMap<>();
    }

    /**
     * 安全检查库存
     */
    private boolean checkStockSafely(Long skuId, Integer quantity) {
        try {
            
            StockCheckReq stockCheckReq = new StockCheckReq();
            stockCheckReq.setSkuId(skuId);
            stockCheckReq.setQuantity(quantity);

            Result<StockCheckResp> result = productRemoteService.checkStock(stockCheckReq);
            
            if (result == null && Result.isError(result) && result.getData() == null) {
                throw new ServiceException("");
            }
        } catch (Exception e) {
            throw new ServiceException("");
        }
        return false;
    }

    /**
     * 计算小计金额
     */
    private BigDecimal calculateSubtotal(BigDecimal price, Integer quantity) {
        if (price == null || quantity == null) {
            return BigDecimal.ZERO;
        }
        return price.multiply(BigDecimal.valueOf(quantity));
    }
}